let models = require('node-require-directory')(__dirname);
let mongoose = require('mongoose');
let config = require('config');
let Promise = require('bluebird');
let _ = require('underscore');
// let findOrCreate = require('mongoose-findorcreate');

mongoose.Promise = Promise;

mongoose.connect('mongodb://' + config.mongodb.host + '/' + config.mongodb.database, function (err) {
    // console.log(err);
});
// global.mongooseConnection = mongoose.createConnection('mongodb://' + config.mongodb.host + '/' + config.mongodb.database);
// global.mongooseConnection.open('mongodb://' + config.mongodb.host + '/' + config.mongodb.database);
global.mongooseConnection = mongoose.connection;
Object.keys(models).forEach(function(key) {
    if (key === 'index') return;
    // add find or create static method
    // models[key].plugin(findOrCreate);
    // add virtual path based on Date path
    executeVirtualPath(models[key]);
    let modelName = capitaliseFirstLetter(key);
    global[modelName] = mongoose.model(modelName, models[key]);
    // promise
    Promise.promisifyAll(global[modelName]);
    Promise.promisifyAll(global[modelName]);
});

global.mongoose = mongoose;

function capitaliseFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}
// add virtual path
function addVirtualPath(schema, property) {
    schema.virtual(property + 'Ms').get(function () {
        if (this[property]) {
            return this[property].getTime();
        }
        return undefined;
    });
}
// execute virtual path
function executeVirtualPath(schema) {
    if (!schema || !schema.obj) {
        return;
    }

    // set schema option
    schema.set('toObject', {getters: true});
    schema.set('toJSON', {getters: true});

    Object.keys(schema.obj).forEach(function (property) {
        if (schema.obj[property] === Date) {
            addVirtualPath(schema, property);
        } else if (_.isObject(schema.obj[property])) {
            let subObj;
            if (_.isArray(schema.obj[property])) {
                subObj = schema.obj[property][0];
            } else {
                subObj = schema.obj[property];
            }
            // object
            if (subObj.type) {
                // type property exist, is not a sub schema
                if (subObj.type === Date) {
                    // type is Date
                    addVirtualPath(schema, property);
                }
            } else {
                // type property not exist, is a sub schema
                executeVirtualPath(subObj);
            }
        }
    });
}
